/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p>Project: javaweb - CountOnline
 * <p>Powered by webrx On 2022-03-11 09:42:18
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@WebListener
public class CountOnline implements HttpSessionListener, HttpSessionAttributeListener {
    public static Map<String,String> map = new HashMap<>();
    public static int count = 0;
    public static Set<String> set = new HashSet<String>();
    /**
     * 只要有人访问，服务器上的动态技术请求 *.jsp *.do *.action 会自动建立session
     * 执行此方法
     *
     * @param se
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        map.put(ctx.getAttribute("ip").toString(),"");
        //HttpSessionListener.super.sessionCreated(se);
        System.out.println("有人上线访问:" + ctx.getAttribute("ip"));
        count++;
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        //HttpSessionListener.super.sessionDestroyed(se);
        System.out.println("下线");
        ServletContext ctx = se.getSession().getServletContext();
        map.remove(ctx.getAttribute("ip").toString());
        //
        count--;
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        ///HttpSessionAttributeListener.super.attributeAdded(event);
        //只要你执行session.setAttribute()
        if(event.getName().equals("account")) {
            System.out.println("登录");
            System.out.println(event.getName());
            System.out.println(event.getValue());
            set.add(event.getValue().toString());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if(event.getName().equals("account")) {
            System.out.println("退出");
            System.out.println(event.getName());
            System.out.println(event.getValue());
            set.remove(event.getValue().toString());
        }
    }

    /**
     * session.setAttribute("account", "aa");
     * session.setAttribute("account", "cc);
     * @param event
     */
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        if(event.getName().equals("account")) {
            System.out.println("重新登录");
            System.out.println(event.getName());
            System.out.println(event.getValue());
        }
    }
}
